import Taro from '@tarojs/taro';
import {
  Avatar,
  Button,
  Cell,
  CountDown,
  Dialog,
} from '@nutui/nutui-react-taro';
import { View, Text } from '@tarojs/components';
import { IconFont } from '@nutui/icons-react-taro';
import { useCallback, useEffect, useState } from 'react';
import { generateUUID } from '@/utils/uuid';
import { priceToString } from '@/utils/price';
import {
  DetailPageType,
  EnumOrderStatus,
  getPaidStopTime,
  IOrder,
  IOrderDisplay,
  IOrderTotal,
  orderStatusFormat,
  orderTotalStatusFormat,
} from '@/types/order';
import './card-order.less';
import { cancel } from '@/utils/wxpay';
import { EnumCrowd, EnumTicketType } from '@/types/ticket';
import { formatDate, formatDate2, formatDateTime } from '@/utils/time';
import request from '@/utils/request';
import { getUser } from '@/utils/user';

interface IProps {
  orderTotal: IOrder;
  refreshList: () => void;
}

const sortDisplayOrder = (orders: IOrderDisplay[]) => {
  return orders.sort((a, b) => {
    if (a.attribute.crowd === EnumCrowd.ADULT) {
      return -1;
    } else if (b.attribute.crowd === EnumCrowd.ADULT) {
      return 1;
    } else {
      return -9;
    }
  });
};


const goDetailPage = (orderTotalId: string, type: string = 'detail') => {
  Taro.navigateTo({
    url: `/pages/order-detail/index?id=${orderTotalId}&type=${type}`,
  });
};

const goPayPage = (orderTotal: IOrder) => {
  const stopTime = getPaidStopTime(orderTotal.createTime);
  const now = new Date().getTime();
  if (stopTime <= now) {
    goDetailPage(orderTotal.id, DetailPageType.DETAIL);
  } else {
    Taro.navigateTo({
      url: `/pages/order-review/index?price=${orderTotal.orderAmount}&orderId=${orderTotal?.id}`,
    });
  }
};

const buttonsRenderUnPaid = (
  orderTotal: IOrder,
  confirmCancel: (orderTotalId: string) => void
) => {
  const stopTime = new Date(orderTotal.createTime).getTime() + 1000 * 60 * 30;
  const now = new Date().getTime();
  return (
    <View className="buttons-unpaid">
      {now < stopTime ? (
        <View className="stop-time">
          剩余
          <CountDown remainingTime={stopTime - now} />
        </View>
      ) : (
        <View className="out-time"></View>
      )}
      <View style={{ height: 24 }}>
        {/* {now < stopTime && (
          <>
            <Button
              type="primary"
              size="mini"
              onClick={() => goPayPage(orderTotal)}>
              付款
            </Button>
          </>
        )} */}
        {/* {now >= stopTime && (
          <Button
            type="default"
            size="mini"
            onClick={() => goDetailPage(orderTotal.id)}>
            详情
          </Button>
        )} */}
      </View>
    </View>
  );
};

const buttonsRenderPaid = (finishOrder: () => void) => {
  return (
    <>
      <Button type="primary" size="mini" onClick={()=>{
        finishOrder()
      }}>
        完成
      </Button>
    </>
  );
};

const buttonRenderDetail = (orderTotal: IOrder) => {
  return null;
  return (
    <Button
      type="default"
      size="mini"
      onClick={() => goDetailPage(orderTotal.id)}>
      详情
    </Button>
  );
};

const buttonsRender = (
  orderTotal: IOrder,
  confirmCancel: (orderTotalId: string) => void,
  finishOrder: () => void
) => {
  if (orderTotal.status === EnumOrderStatus.UNPAID) {
    return buttonsRenderUnPaid(orderTotal, confirmCancel);
  } else if (orderTotal.status === EnumOrderStatus.PAID) {
    return buttonsRenderPaid(finishOrder);
  } else if (
    orderTotal.status === EnumOrderStatus.REFUNDING ||
    orderTotal.status === EnumOrderStatus.EXCEPTION ||
    orderTotal.status === EnumOrderStatus.CANCELED ||
    orderTotal.status === EnumOrderStatus.REFUNDED ||
    orderTotal.status === EnumOrderStatus.USED
  ) {
    return buttonRenderDetail(orderTotal);
  }
};

const isGoPayPage = (orderTotal: IOrder) => {
  if (orderTotal.status === EnumOrderStatus.UNPAID) {
    return true;
  }
  return false;
};

export default function Index(props: IProps) {
  const { orderTotal, refreshList } = props;
  const user = getUser();

  const finishOrder = useCallback(async() => {
    try {
      // 显示加载中提示
      Taro.showLoading({
        title: '处理中...'
      });
      
      // 调用接口完成订单
      const result = await request.get<IOrder[]>('/order/finish-task', {
        userId: user?.id,
        orderId: orderTotal?.id,
      });
      
      // 隐藏加载提示
      Taro.hideLoading();
      
      // 检查结果
      if (result) {
        Taro.showToast({
          title: `订单完成成功`,
          icon: 'success',
        });
        
        // 延迟一下再刷新列表，确保接口处理完毕
        setTimeout(() => {
          refreshList();
        }, 300);
      } else {
        Taro.showToast({
          title: `操作失败，请重试`,
          icon: 'none',
        });
      }
    } catch (error) {
      console.error('完成订单失败:', error);
      Taro.hideLoading();
      Taro.showToast({
        title: `操作失败，请重试`,
        icon: 'none',
      });
    }
  },[user, orderTotal, refreshList]);

  /**
   * 取消订单
   */
  const initCancel = async (orderId: string) => {
    await cancel(
      orderId,
      () => {
        Taro.showToast({
          title: `订单取消成功`,
          icon: 'none',
        });
        refreshList();
      },
      () => {
        Taro.showToast({
          title: `订单取消失败`,
          icon: 'none',
        });
      }
    );
  };

  const confirmCancel = (orderTotalId: string) => {
    Dialog.open('cancel', {
      title: '取消提醒',
      content: '取消操作无法回退，确定取消吗？',
      onConfirm: () => {
        initCancel(orderTotalId);
        Dialog.close('cancel');
      },
      onCancel: () => {
        Dialog.close('cancel');
      },
    });
  };

  return (
    <View className="order-card-order">
      <Cell.Group>
        <Cell
          className="cell-row-1"
          title={
            <View className="order-title">
              {/* // 2025-03-08T01:45:26.906Z 格式转化成 2025-03-08*/}
              <View>订单时间：{formatDate2(orderTotal.createTime)}</View>
              <View className="status">
                {orderStatusFormat(orderTotal.status)}
              </View>
            </View>
          }
        />
        <Cell>
          <View className="order-box">
            <View className="icon-box">
              <Avatar
                size="48"
                icon={
                  <IconFont
                    size={22}
                    fontClassName="icon"
                    color="#000"
                    classPrefix="go-farm"
                    name="avatar"
                  />
                }
                shape="round"
              />
            </View>
            <View className="order-item-wrapper">
              <View className="wrapper-title">
                <View>{orderTotal?.orderType === "trash" ? "扔垃圾" : "取快递"}</View>
                <View>{orderTotal.price}</View>
              </View>
              {
                orderTotal.takeNum ? <View className="wrapper-date">
                  快递数量：{orderTotal.takeNum}
                </View> : null
              }
              {
                orderTotal.takeBigNum ? <View className="wrapper-date">
                  其中大件数量：{orderTotal.takeBigNum}
                </View> : null
              }
              {
                orderTotal.desc ? <View className="wrapper-date">
                  {orderTotal.orderType === "parcel" ? "取件码" : "备注"}：{orderTotal.desc}
                </View> : null
              }
              {
                orderTotal.time && <View className="wrapper-date">
                  预约时间：{orderTotal.time}
                </View>
              }
              {
                orderTotal.timeEnd && <View className="wrapper-date">
                  结束时间：{orderTotal.timeEnd}
                </View>
              }
              {
                orderTotal.takerFinishTime && orderTotal.createTime &&
                 new Date(orderTotal.takerFinishTime).getTime() > new Date(orderTotal.createTime).getTime() && <View className="wrapper-date">
                  上次完成时间：{new Date(orderTotal.takerFinishTime).toLocaleString()}
                </View>
              }
              <View className="wrapper-date">
                地址：{orderTotal.fullAddress}
              </View>
            </View>
          </View>
        </Cell>
        <Cell className="cell-foot">
          <View className="order-buttons">
            {buttonsRender(orderTotal, confirmCancel, finishOrder)}
          </View>
        </Cell>
      </Cell.Group>
    </View>
  );
}
